package com.todod.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.dto.DataLogDto;
import com.todod.entity.QueryEntry;
import com.todod.mapper.DataLogMapper;
import com.todod.model.DataLog;
import com.todod.model.User;
import com.todod.service.IDataLogService;
import com.todod.service.IUserService;

import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gsh
 * @since 2020-10-14
 */
@Service
@Transactional
public class DataLogServiceImpl extends ServiceImpl<DataLogMapper, DataLog> implements IDataLogService {
	@Autowired
	private IUserService iUserService;
	@Autowired
	private DataLogMapper dataLogMapper;

	Logger log = LoggerFactory.getLogger(this.getClass());

	public IPage<DataLogDto> getPage(QueryEntry queryEntry) {
		Page<DataLogDto> page = new Page<DataLogDto>(queryEntry.getPage(), queryEntry.getLimit());

		IPage<DataLogDto> iPage = dataLogMapper.getList(page, queryEntry);

		List<DataLogDto> records = iPage.getRecords();
		for (DataLogDto record : records) {
			User user = iUserService.getById(record.getUserId());
			record.setUserName(user.getNickName());
		}

		return iPage;

	}

	@Override
	public void saveData(Object _userId, String piciNum, String tableName, String type, String content, String zhuId) {
		DataLog dataLog = new DataLog();

		dataLog.setId(SnowflakeIdGenerator.getId());
		if (_userId != null) {
			dataLog.setUserId(Long.parseLong(_userId.toString()));
			dataLog.setCreateUserId(Long.parseLong(_userId.toString()));
		}
		if (zhuId != null && StringUtils.isNotBlank(zhuId)) {
			dataLog.setZhuId(Long.parseLong(zhuId));
		}
		dataLog.setCreateTime(new Date());

		dataLog.setContent(content);
		dataLog.setPiciNum(piciNum);
		dataLog.setTableName(tableName);
		dataLog.setType(type);

		save(dataLog);
	}

	public IPage<DataLogDto> getPage2(QueryEntry queryEntry) {
		Page<DataLogDto> page = new Page<DataLogDto>(queryEntry.getPage(), queryEntry.getLimit());

		IPage<DataLogDto> iPage = dataLogMapper.getList2(page, queryEntry);

		List<DataLogDto> records = iPage.getRecords();
		for (DataLogDto record : records) {
			User user = iUserService.getById(record.getUserId());
			record.setUserName(user.getNickName());
		}

		return iPage;

	}

}
